<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\api\controller\KbxOrder;
use app\common\controller\Selfmcrypt;
use app\wap\controller\Gdimg;
use \think\Cache;
use \think\Controller;
use think\Loader;
use think\Db;
use \think\Cookie;
use \think\Lang;
use app\api\controller\OssController;
use app\api\controller\KbxOther;
class Common extends Controller
{
    /**
     * 清除全部缓存
     * @return [type] [description]
     */
    public function clear()
    {
        if(false == Cache::clear()) {
            return $this->error('清除缓存失败');
        } else {
            return $this->success('清除缓存成功');
        }
    }
    /**
     * 图片上传方法
     * @return [type] [description]
     */
    public function upload($module='admin',$use='admin_thumb')
    {
        if($this->request->file('file')){
            $file = $this->request->file('file');
        }else{
            $res['code']=1;
            $res['msg']='没有上传文件';
            return json($res);
        }
        $module = $this->request->has('module') ? $this->request->param('module') : $module;//模块
        $web_config = Db::name('webconfig')->where('web','web')->find();
        $info = $file->validate(['size'=>$web_config['file_size']*1024,'ext'=>$web_config['file_type']])->rule('date')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $module . DS . $use);

        if($info) {
            //上传OSS
            $object = 'custom/'.md5($info->getSaveName().time()).'.'.$info->getExtension();//想要保存文件的名称
            $file = ROOT_PATH  . 'public'  . DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();//文件路径，必须是本地的
            try{
                $OssController = new OssController();
                $ossClient = $OssController->newOssClient();
                $ossClient->uploadFile($OssController->bucket,$object,$file);
                // 定义全局变量存储图片的oss路径
                $config=config('aliyun_oss');
                $ossimgurl = "https://".$OssController->bucket.".".$config['endpoint']."/".$object;
            } catch(\Exception $e) {
                $res=[
                    'code'=>401,
                    'msg'=>"上传失败".$e
                ];
                return json($res);
            }

            //写入到附件表
            $data = [];
            $data['module'] = $module;
            $data['filename'] = $info->getFilename();//文件名
            $data['filepath'] = $ossimgurl;//文件路径
            $data['fileext'] = $info->getExtension();//文件后缀
            $gd= new Gdimg();
            $data['small_image']='';

            if ( preg_match('/jpg|png|gif|jpeg/',$data['fileext'])){
                //$data['small_image']= $gd->compressImg($data['filename'],$ossimgurl);
            }

            $oldfile = $ossimgurl;
            @$this->img_create_small($oldfile,1000,1000,$oldfile);

            $data['filesize'] = $info->getSize();//文件大小
            $data['create_time'] = time();//时间
            $data['uploadip'] = $this->request->ip();//IP
            $data['user_id'] = Cookie::has('admin') ? Cookie::get('admin') : 0;
            if($data['module'] = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status'] = 1;
                $data['admin_id'] = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use'] = $this->request->has('use') ? $this->request->param('use') : $use;//用处
            $res['id'] = Db::name('attachment')->insertGetId($data);
            $res['src'] = $ossimgurl;
            $res['code'] = 2;
            $res['name'] = $info->getInfo("name");
            addlog($res['id']);//记录日志

            // 删除本地文件
            unlink($file);

            return json($res);
        } else {
            // 上传失败获取错误信息
            return $this->error('上传失败：'.$file->getError());
        }
    }


    //图片上传限制至少800*800
    public function uploadImgLimit800($module='admin',$use='admin_thumb')
    {
        if($this->request->file('file')){
            $file = $this->request->file('file');
        }else{
            $res['code']=1;
            $res['msg']='没有上传文件';
            return json($res);
        }
//        var_dump($file->getInfo('tmp_name'),$file);exit;
        $checkFileResource = $file;
        list($imageWidth,$imageHeight) = getimagesize($file->getInfo('tmp_name'),$checkFileResource);
        if($imageHeight <800 || $imageWidth < 800){
            return $this->error('请上传800*800的图片！');
        }
        $module = $this->request->has('module') ? $this->request->param('module') : $module;//模块
        $web_config = Db::name('webconfig')->where('web','web')->find();
        $info = $file->validate([
            'size'=>$web_config['file_size']*1024,
            'ext'=>$web_config['file_type']
        ])->rule('date')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $module . DS . $use);

        if($info) {
            //上传OSS
            $object = 'custom/'.md5($info->getSaveName().time()).'.'.$info->getExtension();//想要保存文件的名称
            $file = ROOT_PATH  . 'public'  . DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();//文件路径，必须是本地的
            try{
                $OssController = new OssController();
                $ossClient = $OssController->newOssClient();
                $ossClient->uploadFile($OssController->bucket,$object,$file);
                // 定义全局变量存储图片的oss路径
                $config=config('aliyun_oss');
                $ossimgurl = "https://".$OssController->bucket.".".$config['endpoint']."/".$object;
            } catch(\Exception $e) {
                $res=[
                    'code'=>401,
                    'msg'=>"上传失败".$e
                ];
                return json($res);
            }

            //写入到附件表
            $data = [];
            $data['module'] = $module;
            $data['filename'] = $info->getFilename();//文件名
            $data['filepath'] = $ossimgurl;//文件路径
            $data['fileext'] = $info->getExtension();//文件后缀
            $gd= new Gdimg();
            $data['small_image']='';

            if ( preg_match('/jpg|png|gif|jpeg/',$data['fileext'])){
                //$data['small_image']= $gd->compressImg($data['filename'],$ossimgurl);
            }

            $oldfile = $ossimgurl;
            @$this->img_create_small($oldfile,1000,1000,$oldfile);

            $data['filesize'] = $info->getSize();//文件大小
            $data['create_time'] = time();//时间
            $data['uploadip'] = $this->request->ip();//IP
            $data['user_id'] = Cookie::has('admin') ? Cookie::get('admin') : 0;
            if($data['module'] = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status'] = 1;
                $data['admin_id'] = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use'] = $this->request->has('use') ? $this->request->param('use') : $use;//用处
            $res['id'] = Db::name('attachment')->insertGetId($data);
            $res['src'] = $ossimgurl;
            $res['code'] = 2;
            $res['name'] = $info->getInfo("name");
            addlog($res['id']);//记录日志

            // 删除本地文件
            unlink($file);

            return json($res);
        } else {
            // 上传失败获取错误信息
            return $this->error('上传失败：'.$file->getError());
        }
    }
    
    public function img_create_small($big_img, $width, $height, $small_img) {//原始大图地址，缩略图宽度，高度，缩略图地址
        $imgage = getimagesize($big_img); //得到原始大图片
        switch ($imgage[2]) { // 图像类型判断
            case 1:
                $im = imagecreatefromgif($big_img);
                break;
            case 2:
                $im = imagecreatefromjpeg($big_img);
                break;
            case 3:
                $im = imagecreatefrompng($big_img);
                break;
        }
        $src_W = $imgage[0]; //获取大图片宽度
        $src_H = $imgage[1]; //获取大图片高度

        if( $src_W > $width || $src_H > $height)
        {
            //计算缩放比例
            $scale = min($width / $src_W, $height / $src_H);
            //设置缩略图的坐标及宽度和高度

            $width  = $src_W * $scale;
            $height = $src_H * $scale;

            $tn = imagecreatetruecolor($width, $height); //创建缩略图
            imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小

            imagejpeg($tn, $small_img); //输出图像
        }
    }




    /**
     * 登录
     * @return [type] [description]
     */
    public function login()
    {
        if(Cookie::has('admin') == false) {
            if($this->request->isPost()) {
                //是登录操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require|alphaDash', '用户名不能为空|用户名格式只能是字母、数字、——或_'],
                    ['password', 'require', '密码不能为空'],
                    ['captcha','require|captcha','验证码不能为空|验证码不正确'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $name = Db::name('admin')->where('name',trim($post['name']))->find();
                if(empty($name)) {
                    //不存在该用户名
                    return $this->error('用户名不存在');
                } else {
                    //验证密码
                    $post['password'] = password($post['password']);
                    if($name['password'] != $post['password']) {
                        return $this->error('密码错误');
                    } else {
                        //是否记住账号
                        if(!empty($post['remember']) and $post['remember'] == 1) {
                            //检查当前有没有记住的账号
                            if(Cookie::has('usermember')) {
                                Cookie::delete('usermember');
                            }
                            //保存新的
                            Cookie::forever('usermember',$post['name']);
                        } else {
                            //未选择记住账号，或属于取消操作
                            if(Cookie::has('usermember')) {
                                Cookie::delete('usermember');
                            }
                        }
                        Cookie::set("admin",$name['id'],43200); //保存新的,最长为12小时
                        $this->updateCustomMade('self');//设置自营定制师身份
                        //记录登录时间和ip
                        Db::name('admin')->where('id',$name['id'])->update(['login_ip' =>  $this->request->ip(),'login_time' => time()]);
                        //记录操作日志
                        addlog();
                        //Db::name('admin_log')->data(['ip' =>  $this->request->ip(),'create_time' => time(),'name'=>'管理员登录','admin_id'=>$name['id']])->insert();
                        return $this->success('登录成功,正在跳转...','admin/index/index');
                        //$this->redirect('admin/index/index');
                    }
                }
            } else {
                if(Cookie::has('usermember')) {
                    $this->assign('usermember',Cookie::get('usermember'));
                }
                return $this->fetch();
            }
        } else {
            $admin_id = Cookie::get('admin');
            $adminCate = db('admin')->find($admin_id);
            if($adminCate['admin_cate_id']==28){
                //清除登陆状态
                Cookie::delete('admin');
                return $this->fetch();
            }
            $this->redirect('admin/index/index');
        }
    }

    /**
     * 管理员退出，清除名字为admin的cookie
     * @return [type] [description]
     */
    public function logout()
    {
        Cookie::delete('admin');

        $tempcookie = Cookie::get('admin');
        if(!empty($tempcookie)) {
            Cookie::delete('selfCustomMade');
            return $this->error('退出失败');
        } else {
            return $this->success('正在退出...','admin/common/login');
        }
    }

    //订单系统或TOB系统账号自动登录【接口调用】
    public function autoLogin()
    {
        //获取加密后token
        $token = input("token",'');
        //是否首次刷新 【缓存所有tob账号的token记录】
        $to_token_list = Cache::get('tob_token_list');
        $to_token_list = empty($to_token_list)?[]:$to_token_list;
        //非首次请求页面
        if(in_array($token,$to_token_list)){
            $adminid = Cookie::get('admin');
            if(empty($adminid)){
                return '验权失败';
            }
            return ['code'=>200,'msg'=>'succcess','data'=>$adminid];
        }
        //添加新的token
        $to_token_list[] = $token;
        $list_expire = date('Y-m-d',strtotime('+1 day',time()));
        Cache::set('tob_token_list',$to_token_list,new \DateTime($list_expire));
        //解密token
        $token = (new Selfmcrypt())->decode($token);
//        var_dump($token);exit;
        //用户真正的鉴权token
        if(empty($token)){
            return '缺少token参数';
        }
        //验权
        $auth = (new KbxOther())->getAdminInfoByToken(['token'=>$token]);
        //$auth['account'] = 'zhenxing@kuaibangxing.com';
        if(empty($auth['msg'])){
            return '验权失败';
        }
        $account = $auth['msg'];

        $adminInfo = db('admin')->where(['name'=>$account])->find();
        if(empty($adminInfo)){
            return '账号不存在';
        }
        //判断是否是允许通过鉴权的路由
        $auth_route = $this->checkAuthRoute();
        if(!$auth_route){
            return "路由不允许访问";
        }
        Cookie::set("admin",$adminInfo['id'],43200); //保存新的,最长为12小时
        $this->updateCustomMade('partner');//设置合作商定制师身份
        //记录登录时间和ip
        Db::name('admin')->where('id',$adminInfo['id'])->update(['login_ip' =>  $this->request->ip(),'login_time' => time()]);
        //记录操作日志
        addlog();
        //跳转到定制页面
        $tripid = input('id',0);
        if(!empty($tripid)){
            $res = db('trip')->where(['id'=>$tripid])->find();
            if(empty($res)){
                return '定制行程不存在';
            }else{
                //检查定制归属 模板查看开放给所有人
                $tripAdminInfo = db('admin')->find($res['adminid']);//定制师账号
                if(empty($adminInfo) ||
                    empty($tripAdminInfo) ||
                    $adminInfo['company_id']!==$tripAdminInfo['company_id'] && empty($res['is_template']))
                {
                    return '您无权查看此定制';
                }
            }
        }
        return ['code'=>200,'msg'=>'succcess','data'=>$adminInfo['id']];
    }

    //合作商定制师退出登陆
    public function autoLogout()
    {
        Cookie::delete('admin');
        $tempcookie = Cookie::get('admin');
        if(!empty($tempcookie)) {
            $this->deleteCustomMade();
            return $this->error('退出失败');
        } else {
            return $this->success('静默退出',url('admin/common/login'));
        }
    }

    protected function updateCustomMade($region='self')
    {
        if($region=='self'){
            Cookie::set('selfCustomMade',true,12*3600);//设置自营定制师
            Cookie::delete('partnerCustomMade');
        }elseif($region=='partner'){
            Cookie::set('partnerCustomMade',true,12*3600);//设置合作商定制师
            Cookie::delete('selfCustomMade');
        }
    }

    //删除定制师身份
    protected function deleteCustomMade()
    {
        Cookie::delete('admin');
        Cookie::delete('partnerCustomMade');
        Cookie::delete('selfCustomMade');
    }

    //验证路由是否允许通过
    public function checkAuthRoute()
    {
        $allow_auth_route = ['admin/quicktrip/tripmakepartner','admin/trip/partnerpreview'];
        $module = strtolower($this->request->module());
        $controller = strtolower($this->request->controller());
        $action = strtolower($this->request->action());
        //var_dump(in_array($module.'/'.$controller.'/'.$action,$allow_auth_route));exit;
        return in_array($module.'/'.$controller.'/'.$action,$allow_auth_route);
    }

    //tob鉴权失败提示页面
    public function tips()
    {
        $this->deleteCustomMade();
        return $this->fetch();
    }
    public function _empty()
    {
        //未匹配到路由跳转到首页
        return redirect(url('admin/index/index'));
    }


}
